package cease.util;

import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

/**
 * @author dhf
 */
public class EmailUtil {
    private static final Pattern emailPattern = Pattern
            .compile("\\b(^['_A-Za-z0-9-]+(\\.['_A-Za-z0-9-]+)*@([A-Za-z0-9-])+(\\.[A-Za-z0-9-]+)*((\\.[A-Za-z0-9]{2,})|(\\.[A-Za-z0-9]{2,}\\.[A-Za-z0-9]{2,}))$)\\b");

    private static final Pattern domainPattern = Pattern
            .compile("([A-Za-z0-9-])+(\\.[A-Za-z0-9-]+)*((\\.[A-Za-z0-9]{2,})|(\\.[A-Za-z0-9]{2,}\\.[A-Za-z0-9]{2,}))$\\b");

    public static boolean isLegal(String email, boolean strict) {
        if (null == email) {
            return false;
        }
        if (strict) {
            return emailPattern.matcher(email).matches();
        } else {
            return (null != getUsername(email));
        }
    }

    /**
     * 取出某邮箱地址对应的域
     **/
    public static String getDomain(String email) {
        if (null == email) {
            return null;
        }
        int i = email.indexOf('@');
        if (-1 != i) {
            String domain = email.substring(i + 1);
            if (domainPattern.matcher(domain).matches()) {
                return domain;
            } else {
                return null;
            }
        }
        return null;
    }

    /**
     * 返回邮箱地址中的用户名部分
     * 
     * @param email
     * @return
     */
    public static String getUsername(String email) {
        if (null == email) {
            return null;
        }
        if (null == getDomain(email)) {
            return null;
        }
        int i = email.indexOf('@');
        if (-1 != i) {
            return StringUtils.trimToNull(email.substring(0, i));
        }
        return null;
    }
}
